<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }"> 首页 </el-breadcrumb-item>
      <el-breadcrumb-item> 商品管理 </el-breadcrumb-item>
      <el-breadcrumb-item> 参数列表 </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-alert
        title="注意：只能允许为第三级别分类设置相关参数"
        type="warning"
        effect="light"
        show-icon
        :closable="false"
      >
      </el-alert>

      <el-row class="cat_opt">
        <el-col :span="24" :offset="0">
          <span> 选择商品分类: </span>
          <el-cascader
            :options="cateList"
            v-model="selectedCateKeys"
            clearable
            filterable
            :show-all-levels="false"
            :props="cateOption"
            @change="cascaderChange()"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs
        v-model="activeName"
        tab-position="top"
        @tab-click="handleTabClick"
      >
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParmasDialogVisibled = true"
          >
            添加参数
          </el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  size="normal"
                  effect="light"
                  closable
                  @close="removeTag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  ref="saveTagInput"
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  size="small"
                  v-model="scope.row.inputValue"
                  clearable
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  新建
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="removeparams(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            @click="addParmasDialogVisibled = true"
            :disabled="isBtnDisabled"
          >
            添加属性
          </el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  size="normal"
                  effect="light"
                  closable
                  @close="removeTag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  size="small"
                  v-model="scope.row.inputValue"
                  clearable
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  新建
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="removeparams(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数/静态属性 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParmasDialogVisibled"
      width="30%"
      @close="addParmasDialogClosed"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
        size="normal"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addParmasDialogVisibled = false">取消</el-button>
        <el-button type="primary" @click="addParams">确认</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数/静态属性 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisibled"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="addFormRules"
        label-width="100px"
        :inline="false"
        size="normal"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editDialogVisibled = false">取消</el-button>
        <el-button type="primary" @click="editParam">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      cateList: [],
      cateOption: { value: 'cat_id', label: 'cat_name', childern: 'children' },
      selectedCateKeys: [],
      // 激活标签
      activeName: 'many',
      isDisabled: true,
      manyTableData: [],
      onlyTableData: [],
      addParmasDialogVisibled: false,
      //   添加参数的表单数据对象
      addForm: { attr_name: '' },
      //   添加参数的校验规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisibled: false,
      editForm: { attr_name: '' }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    async cascaderChange() {
      console.log(this.selectedCateKeys)
      this.getparamsData()
    },
    handleTabClick() {
      console.log(this.activeName)
      this.getparamsData()
    },
    // 获取参数数据列表
    async getparamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        //   获取参数列表失败
        return this.$message.error(res.meta.msg)
      }
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(' ')
          : []
        element.inputValue = ''
        element.inputVisible = false
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(res.data)
    },
    addParmasDialogClosed() {
      // 添加属性对话框关闭
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加属性失败')
        }
        this.$message.success('添加成功')
        this.getparamsData()
        this.addParmasDialogVisibled = false
      })
    },
    //
    async showEditDialog(obj) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${obj.attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      this.editForm = res.data
      this.editDialogVisibled = true
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisibled = false
    },
    editParam() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_sel: this.activeName,
            attr_name: this.editForm.attr_name
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getparamsData()
        this.editDialogVisibled = false
      })
    },
    removeparams(id) {
      this.$confirm('此操作将永久删除此项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          )
          if (res.meta.status !== 200) {
            this.$message.error('删除错误')
          }
          this.getparamsData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 文本框失去焦点
    async handleInputConfirm(item) {
      if (item.inputValue.trim().length === 0) {
        item.inputValue = ''
        item.inputVisible = false
        return
      }
      item.attr_vals.push(item.inputValue.replaceAll(' ', ''))
      item.inputValue = ''
      item.inputVisible = false
      this.saveAttrVals(item)
    },
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('编辑标签失败')
      }
      this.$message.success('编辑参数项成功')
    },
    showInput(item) {
      item.inputVisible = true
      // nextTick 当页面元素被重新渲染，才指定回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    removeTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length === 3) {
        return false
      }
      return true
    },
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.input-new-tag {
  width: 100px;
}
</style>
